package org.xiaodongwei.jvm.load;

import org.xiaodongwei.jvm.utils.Log;
import tech.medivh.classpy.classfile.ClassFile;
import tech.medivh.classpy.classfile.ClassFileParser;

import java.io.File;
import java.nio.file.Files;
import java.util.List;
import java.util.Objects;

/**
 * 类加载器
 */
public class BootstrapClassLoader {

    private List<String> classPaths;

    public BootstrapClassLoader(List<String> classPaths) {
        this.classPaths = classPaths;
    }

    /**
     * 加载类
     * @param fullClassNamePath：；类的全类名
     */
    public ClassFile loadClass(String fullClassNamePath) throws ClassNotFoundException {
        if (classPaths == null || classPaths.size() <= 0) return null;
        if (!findClass(fullClassNamePath)) {
            return classPaths.stream()
                    .map(classPath -> tryLoadClass(fullClassNamePath, classPath))
                    .filter(Objects::nonNull)
                    .findAny()
                    .orElseThrow(() -> new ClassNotFoundException(fullClassNamePath + "找不到"));
        }
        return null;
    }

    /**
     * 搜索当前类是否已经被加载, 遍历classPath下面的所有路径来加载当前类
     * @param fullClassNamePath：类的全类名
     */
    public boolean findClass(String fullClassNamePath) {

        return false;
    }

    /**
     * 尝试加载
     * @param fullClassNamePath：类的全类名
     * @param classPath: 搜索路径
     */
    private ClassFile tryLoadClass(String fullClassNamePath, String classPath) {
        File classFilePath = new File(classPath, fullClassNamePath.replace(".", File.separator) + ".class");
        if (!classFilePath.exists()) {
            return null;
        }
        try {
            byte[] bytes = Files.readAllBytes(classFilePath.toPath());
            return new ClassFileParser().parse(bytes);
        } catch (Exception e) {
            return null;
        }
    }
}
